package com.naizhuai.ui.mianbusiness.setting;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.naizhuai.R;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.entity.QRCodeScanBean;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.PermissionRequest;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;

/**
 * 使用demo：ManageTestFunctionActivity
 * 扫描二维码的
 */
public class ManageScanQRCodeActivity extends BaseActivity implements QRCodeView.Delegate, View.OnClickListener {
    @BindView(R.id.zxingview)
    QRCodeView zXingView;
    @BindView(R.id.scan_icon)
    TextView scanTxt;
    @BindView(R.id.scan_image)
    TextView imgTxt;
    private static final String PATH_KEY = "path_key";
    private static ScanHandler scanHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        scanTxt.setSelected(false);
        imgTxt.setSelected(false);
        scanHandler=new ScanHandler(this);
        getPermissionRequest().request(new PermissionRequest.PermissionCallback() {
            @Override
            public void onSuccessful() {
                initQrCode();
            }

            @Override
            public void onFailure() {
                shortToast(getText(R.string.no_camera_permission).toString());
                onBackPressed();
            }
        }, new String[]{Manifest.permission.CAMERA});
    }

    private void initQrCode() {
        scanTxt.setSelected(true);
        imgTxt.setSelected(false);
        zXingView.setDelegate(this);
        zXingView.startSpot();
    }


    @Override
    public int getLayoutId() {
        return R.layout.test_activity_scan_qrcode_layout;
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();
        NaizhuAILog.e("result:" + result);
        QRCodeScanBean bean = QRCodeScanBean.getScanObject(result);
        if (bean != null) {
//            Toast.makeText(this, new Gson().toJson(bean), Toast.LENGTH_SHORT).show();
        } else
            shortToast("扫描错误");
        sendIntentBack(bean,this);
    }

    private static void sendIntentBack(QRCodeScanBean bean, Activity context) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(QRCodeScanBean.SCAN_DATA_KEY, bean);
        intent.putExtras(bundle);
        context.setResult(QRCodeScanBean.SCAN_CODE, intent);
        context.finish();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        if (vibrator != null) {
            vibrator.vibrate(200);
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Toast.makeText(this, "打开相机出错", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        zXingView.startCamera();
//        mQRCodeView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT);
        zXingView.showScanRect();
    }

    @Override
    protected void onStop() {
        zXingView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        zXingView.onDestroy();
        super.onDestroy();
    }

    @OnClick({R.id.scan_icon, R.id.scan_image,R.id.base_back_icon})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.scan_icon:
                scanTxt.setSelected(true);
                imgTxt.setSelected(false);
                break;
            case R.id.scan_image:
                imgTxt.setSelected(true);
                scanTxt.setSelected(false);
                Album.image(this) // 选择图片。
                        .singleChoice()
                        .requestCode(200)
                        .onCancel(new Action<String>() {
                            @Override
                            public void onAction(int requestCode, @NonNull String result) {
                                scanTxt.setSelected(true);
                                imgTxt.setSelected(false);
                            }
                        })
                        .onResult(new Action<ArrayList<AlbumFile>>() {
                            @Override
                            public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                new ScanThread(result.get(0).getPath()).start();
                            }
                        }).start();

                break;
            case R.id.base_back_icon:
                onBackPressed();
                break;
        }
    }

    class ScanThread extends Thread {

        private String pathStr;

        public ScanThread(String pathStr) {
            this.pathStr = pathStr;
        }

        @Override
        public void run() {
            String qrResult = QRCodeDecoder.syncDecodeQRCode(pathStr);
            NaizhuAILog.e("result="+qrResult);
            Message msg=new Message();
            Bundle bundle=new Bundle();
            bundle.putString(PATH_KEY,qrResult);
            msg.setData(bundle);
            scanHandler.sendMessage(msg);
        }
    }

    static class ScanHandler extends Handler {
        private WeakReference<BaseActivity> mContext;

        public ScanHandler (BaseActivity activity){
            mContext=new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if(mContext.get()==null)
                return;
            Bundle bundle = msg.getData();
            String result = "";
            if (bundle != null)
                result=bundle.getString(PATH_KEY, "");
            NaizhuAILog.e("result="+result);
            QRCodeScanBean bean = QRCodeScanBean.getScanObject(result);
            sendIntentBack(bean,mContext.get());
        }
    }


}
